﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.Reflection;
using System.IO;
using System.Xml;
using System.Text.RegularExpressions;


namespace GeneratorAddin {
    [RunInstaller(true)]
    public partial class Installer1 : Installer {
        public Installer1() {
            InitializeComponent();
        }
        private string GenerateAddinContent() {
            XmlDocument doc = new XmlDocument();
            string installationPath = base.Context.Parameters["AssemblyPath"];
            
            string addinResourceFile = Assembly.GetExecutingAssembly().GetName().Name + ".GeneratorAddin.AddIn";

            using (Stream resourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(addinResourceFile)) {
                doc.Load(resourceStream);
            }

            //XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
            //nsmgr.AddNamespace("", "http://schemas.microsoft.com/AutomationExtensibility");
            //XmlNode node = doc.DocumentElement.SelectSingleNode("//Extensibility/Addin/Assembly", nsmgr);
            //node.Value = installationPath;
            //return doc.OuterXml;

            //i'm to stupid to make the above work... so we'll just do it here. i may die, btw.
            string text = doc.OuterXml;
            Regex reg = new Regex("<Assembly>.*?</Assembly>");
            return reg.Replace(text, "<Assembly>" + installationPath + "</Assembly>");
        }
        private string getAddinPath() {
            return Path.Combine(Environment.GetEnvironmentVariable("ALLUSERSPROFILE"), @"Application Data\Microsoft\MSEnvShared\Addins\GeneratorAddin.AddIn");
        }
        public override void Install(IDictionary stateSaver) {
            base.Install(stateSaver);
            FileInfo f = new FileInfo(getAddinPath());
            
            if (!f.Directory.Exists)
                f.Directory.Create();

            if (!f.Exists) {
                using (FileStream stream = f.OpenWrite()) {
                    using (XmlTextWriter w = new XmlTextWriter(stream, System.Text.Encoding.Unicode)) {
                        w.WriteRaw(GenerateAddinContent());
                    }
                }
            }
        }
        public override void Uninstall(IDictionary savedState) {
            base.Uninstall(savedState);
            FileInfo f = new FileInfo(getAddinPath());
            if (f.Exists) {
                f.Delete();
            }
        }
        public override void Rollback(IDictionary savedState) {
            base.Rollback(savedState);
            try {
                FileInfo f = new FileInfo(getAddinPath());
                if (f.Exists) {
                    f.Delete();
                }
            } catch { 
                //ok, so it didn't delete the file. don't care.
            }
        }

        private void Installer1_AfterInstall(object sender, InstallEventArgs e) {
            FileInfo uninstaller = new FileInfo(Path.Combine(new FileInfo(base.Context.Parameters["AssemblyPath"]).DirectoryName,"uninstall.bat"));
            if (uninstaller.Exists) {
                uninstaller.Delete();
            }
            using (FileStream stream = uninstaller.OpenWrite()) {
                using (StreamWriter w = new StreamWriter(stream)) {
                    w.Write("start MsiExec.exe /x" + base.Context.Parameters["ProductCode"] );
                }
            }
        }
    }
}
